package utils;

import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.RunnableScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author zjh
 */
@Component
public class TaskUtils {

    private static ScheduledThreadPoolExecutor EXECUTOR = new ScheduledThreadPoolExecutor(16);
    private static Map<String, RunnableScheduledFuture<?>> map = new HashMap<>();

    /**
     * 延迟执行任务
     *
     * @param taskId  事件id
     * @param runnable 任务
     * @param delay    延迟时间 分钟
     */
    public static void schedule(String taskId, Runnable runnable, int delay) {
        RunnableScheduledFuture<?> schedule = (RunnableScheduledFuture<?>) EXECUTOR.schedule(runnable, delay, TimeUnit.MINUTES);
        RunnableScheduledFuture<?> sch = map.put(taskId, schedule);
        System.out.println("{}事件创建延时任务成功" + taskId);
        if (sch != null) {
            //丢弃
            EXECUTOR.remove(sch);
        }
    }

    /**
     * 延迟执行任务
     *
     * @param taskId       taskId
     * @param callable 任务
     * @param delay    延迟时间 分钟
     */
    public static <T> T schedule(String taskId, Callable<T> callable, int delay) {
        RunnableScheduledFuture<T> schedule = (RunnableScheduledFuture<T>) EXECUTOR.schedule(callable, delay, TimeUnit.MINUTES);
        RunnableScheduledFuture<?> sch = map.put(taskId, schedule);
        System.out.println("创建id为{}的延时任务成功" + taskId);
        if (sch != null) {
            //丢弃
            EXECUTOR.remove(sch);
        }
        try {
            return schedule.get();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 延迟执行任务
     *
     * @param runnable 任务
     * @param delay    延迟时间
     * @param unit     延迟时间单位
     */
    public static void schedule(Runnable runnable, int delay, TimeUnit unit) {
        EXECUTOR.schedule(runnable, delay, unit);
        System.out.println("创建延时任务成功");
    }

    /**
     * 移除任务
     *
     * @param taskId 任务id
     */
    public static void remove(String taskId) {
        RunnableScheduledFuture<?> sch = map.remove(taskId);
        if (sch != null) {
            //丢弃
            EXECUTOR.remove(sch);
            System.out.println("删除{}任务成功" + taskId);
        } else {
            System.out.println("{}任务不存在" + taskId);
        }
    }

}

